import { GRAPHQL_API } from "./constants";
import axios from 'axios';

export const getGraphql = () => {
    console.log("GRAPHQL_API::", GRAPHQL_API);

    const query = `
    query bookDetails {
      bookById(id: "book-1") {
        id
        name
        pageCount
        author {
          id
          firstName
          lastName
        }
      }
    }
    `;

    fetch(GRAPHQL_API, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            query: query  // 你的GraphQL查询
        })
    })
        .then(response => response.json())
        .then(data => console.log("data graphql::", data))  // 打印返回结果
        .catch(error => console.error("error graphql::", error));
}


export async function healthPost() {
    const url = "http://localhost:8080/graphql"; // 注意端口号
    const headers = {"Content-Type": "application/json"};

    // 简单查询测试（查询服务是否正常）
    const query = `
    query {
      __schema {
        types {
          name
        }
      }
    }
    `;

    try {
        const response = await axios.post(url, { query }, { headers });
        console.log("healthPost 状态码:", response.status);
        console.log("healthPost 响应内容:", response.data);
    } catch (error) {
        console.error("healthPost 请求失败:", error);
    }
}


export async function getBook() {
    // GraphQL 端点 URL
    const url = "http://localhost:8080/graphql"; // 替换为实际的 GraphQL 端点 URL

    // GraphQL 查询
    const query = `
    query bookDetails {
      bookById(id: "book-1") {
        id
        name
        pageCount
        author {
          id
          firstName
          lastName
        }
      }
    }
    `;

    // 构建请求头
    const headers = {
        "Content-Type": "application/json",
    };

    try {
        const response = await axios.post(url, { query }, { headers });
        console.log("getBook 返回值:", JSON.stringify(response.data, null, 2));
    } catch (error) {
        console.log(`getBook 请求失败，状态码: ${error.response?.status || '未知'}`);
        console.log(error.response?.data || error.message);
    }
}

// 使用示例
healthPost();
getBook();